package com.defysoft.waukids;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;



import com.defysoft.waukids.album.AlbumDetailActivity;
import com.defysoft.waukids.diary.DiaryDetailActivity;
import com.defysoft.waukids.main.Main_Intro;
import com.defysoft.waukids.main.Main_MainFrame;
import com.defysoft.waukids.message.Message_Detail_Activity;
import com.defysoft.waukids.notice.NoticeDetailActivity;

public class GCMIntentService extends IntentService {
	String push_sendtype, Mes_Category;
	int push_pkcode, push_stucode;
	
	private static final String TAG = "GCMIntentService";
	private SharedPreferences check_notice;
	SharedPreferences sharedPreferences;

	Sqlite_Connect sc;
	Intent sendintent;
	/**
	 * Constructor
	 */
	
	//방해금지시간대 설정
	String now_date;
	int now_time, startTime, stopTime, startCheck, stopCheck;
	long now = System.currentTimeMillis();
	Date date = new Date(now);
	int sound, vibration = 0;
	SimpleDateFormat CurHourFormat = new SimpleDateFormat("HH");
	SimpleDateFormat CurMinuteFormat = new SimpleDateFormat("mm");
	
	//사진첩 원장님.선생님 푸시받지 않기위한 설정용.
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;	
	
	public GCMIntentService() {
		super(BasicInfo.PROJECT_ID);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		psf= new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		
		sendintent = new Intent();
		//Sqllite
		push_stucode = Integer.parseInt(intent.getStringExtra(PublicConstant.PUSH_CODE));
		push_pkcode = Integer.parseInt(intent.getStringExtra(PublicConstant.PUSH_PK_CODE));
		sc = new Sqlite_Connect(this);
		sc.insert_Notice(push_pkcode, push_stucode);
		
		
		// 어플 켜짐 유무 확인
		boolean onapp = true; 
		ActivityManager am = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
		ComponentName topActivity = taskInfo.get(0).topActivity; // 어플이 켜졌는지 확인을 위해 현재켜진 어플의 액티비티 이름 얻음

		//패키지 동일
		if (topActivity.getPackageName().equals("com.defysoft.waukids")) {
			onapp = true;
		} else {
			onapp = false;
		}
		push_sendtype =intent.getStringExtra(PublicConstant.PUSH_SENDTYPE);
		sharedPreferences = getSharedPreferences("notifications", MODE_PRIVATE);
		
		if (sharedPreferences.getString("PUSH_NOTIFICATIONS", "0").equals("0")) {
			//소리설정
			sound = sharedPreferences.getString("PUSH_SOUND", "0").equals(
					"0") ? Notification.DEFAULT_SOUND: 0;
			//진동설정
			vibration = sharedPreferences.getString("PUSH_VIBRATION", "0")
					.equals("0") ? Notification.DEFAULT_VIBRATE : 0;
			
//방해금지시간대 설정.
			// 1. 현재날짜시간

			int now_hour = Integer.parseInt(CurHourFormat.format(date));
			int now_minute = Integer.parseInt(CurMinuteFormat.format(date));
			now_time = now_hour*100 + now_minute;
			startTime = sharedPreferences.getInt("START_TIMEPICKER_TIME", 0);
			stopTime = sharedPreferences.getInt("STOP_TIMEPICKER_TIME", 0);
			startCheck = sharedPreferences.getInt("START_TIMEPICKER_CHECK", 0);
			stopCheck = sharedPreferences.getInt("STOP_TIMEPICKER_CHECK", 0);

			if (now_time < startTime && startCheck == 1) {
				 sound = 0;
				 vibration = 0;
			}
			if (now_time >= stopTime && stopCheck == 1) {
				sound = 0;
				vibration = 0;
			}
			
			
			// 메시지 좌측의 아이콘
			NotificationManager mNotificationManager = (NotificationManager) this
					.getSystemService(Context.NOTIFICATION_SERVICE);
			
			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
					this);
			mBuilder.setSmallIcon(R.drawable.ic_launcher);
			mBuilder.setContentTitle(intent.getStringExtra(PublicConstant.PUSH_NAME));
			mBuilder.setAutoCancel(true);
			mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(intent.getStringExtra(PublicConstant.PUSH_SUB)));
			mBuilder.setContentText(intent.getStringExtra(PublicConstant.PUSH_SUBNAME));
			mBuilder.setDefaults(sound | vibration);
			
			//상태별 GCM
			
if ((Integer.parseInt(push_sendtype))>= 10000 && (Integer.parseInt(push_sendtype)) < 20000) {
	
		
//현장학습
			if (push_sendtype.equals(PublicConstant.GCM_FIELD_CODE)) {
					if(!onapp){
						mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
								new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
					}else if((topActivity.getClassName().equals("com.defysoft.waukids.main.Main_MainFrame"))){		//메인프레임까지 동일
					//alert띄움.
				} else {			//다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, new Intent(getApplicationContext(), Main_MainFrame.class), PendingIntent.FLAG_UPDATE_CURRENT));
				}
					
					if (sharedPreferences.getString("PUSH_FIELD", "0").equals("0")) {
					mNotificationManager.notify(Integer.parseInt(intent
							.getStringExtra(PublicConstant.PUSH_CODE)),
							mBuilder.build());
					}

//공지사항_sqllite
			} else  if (push_sendtype.equals(PublicConstant.GCM_NOTIEC_CODE)) {
				sc.insert_New_Notice(push_pkcode, push_stucode);				
				if(!onapp){		//꺼져있음.	
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getBroadcast(getApplicationContext(),0, 
							new Intent("com.defysoft.waukids.NEWFRESH")
							.putExtra("PUSH_SENDTYPE", intent.getStringExtra(PublicConstant.PUSH_SENDTYPE))
							.putExtra("PK_Not_Code",Integer.toString(push_pkcode))
							/*.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))*/
							, PendingIntent.FLAG_UPDATE_CURRENT));
				}
				
				//푸시 아예 안띄움.
				if (sharedPreferences.getString("PUSH_NOTICE", "0").equals("0")) {
					if (member.Rank.equals("3")) {		//학부모일때만 푸시
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
					}
				}

//공지사항_sqllite+new없음.				
			}else if(push_sendtype.equals(PublicConstant.GCM_NOTIEC_CODE_NONNEW)){
				if(!onapp){		//꺼져있음.	
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), NoticeDetailActivity.class)
							.putExtra("PK_Not_Code",Integer.toString(push_pkcode))
							/*.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))*/
							, PendingIntent.FLAG_UPDATE_CURRENT));
				}
				
				//푸시 아예 안띄움.
				if (sharedPreferences.getString("PUSH_NOTICE", "0").equals("0")) {
					if (member.Rank.equals("3")) {		//학부모일때만 푸시
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
					}
				}				
				
				
			
//원아수첩_sqllite
			}else if (push_sendtype.equals(PublicConstant.GCM_DIARY_CODE)) {
				sc.insert_New_Diary(push_pkcode, push_stucode);
				if(!onapp){		//꺼져있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getBroadcast(getApplicationContext(),0, 
							new Intent("com.defysoft.waukids.NEWFRESH")
							.putExtra("PUSH_SENDTYPE", intent.getStringExtra(PublicConstant.PUSH_SENDTYPE))
							.putExtra("PK_Dia_Code",Integer.toString(push_pkcode))
							/*.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))*/
							, PendingIntent.FLAG_UPDATE_CURRENT));
				}
				
				//원아수첩 옵션설정 없음.
				if (member.Rank.equals("3")) {		//학부모일때만 푸시
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
				
				}
//사진첩_sqllite
			} else if (push_sendtype.equals(PublicConstant.GCM_PHOTO_CODE)) {
				sc.insert_New_Photo(push_pkcode, push_stucode);
				if(!onapp){
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), AlbumDetailActivity.class)
							.putExtra("PK_Alb_Code",Integer.toString(push_pkcode))
							/*.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))*/
							, PendingIntent.FLAG_UPDATE_CURRENT));
				}
				//푸시 켜지고 꺼짐.
				/*if (member.Rank.equals("3")) {
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
				}*/
				
//사진첩_sqllite+new없음.
			} else if (push_sendtype.equals(PublicConstant.GCM_PHOTO_CODE_NONNEW)) {
				//sc.insert_New_Photo(push_pkcode, push_stucode);
				if(!onapp){
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), AlbumDetailActivity.class)
							.putExtra("PK_Alb_Code",Integer.toString(push_pkcode))
							/*.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))*/
							, PendingIntent.FLAG_UPDATE_CURRENT));
				}
				//푸시 켜지고 꺼짐.
				/*if (member.Rank.equals("3")) {
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
				}*/
				
//캘린더_sqllite
			}
			else if (push_sendtype.equals(PublicConstant.GCM_CALENDAR_CODE)) {
				sc.insert_New_Cal(push_pkcode, push_stucode);	
				if(!onapp){
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Main_MainFrame.class), PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
					/*mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
							new Intent(getApplicationContext(), Calendar_Main_Attend.class)
							.putExtra("PK_Mes_Code",Integer.toString(push_pkcode))
							.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))
							, PendingIntent.FLAG_UPDATE_CURRENT));*/
				}
				//푸시안함.
				/*mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());*/
			
//메세지요청서_sqllite
			} else if (push_sendtype.equals(PublicConstant.GCM_MESSAGE_CODE) && sharedPreferences.getString("PUSH_DOCUMENT", "0").equals("0")) {
				sc.insert_New_Mas(push_pkcode, push_stucode);		
				//메세지 요청서 종류.

				if(!onapp){	//꺼져있음.
					mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),PublicConstant.START_MESSAGE, 
							new Intent(getApplicationContext(), Main_Intro.class).putExtra("GO_MESSAGE", "GO")
							.putExtra("PK_Mes_Code", push_pkcode)
						.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))
						, PendingIntent.FLAG_UPDATE_CURRENT));
				} else if(topActivity.getPackageName().equals("com.defysoft.waukids")){			//켜져있고. 다른곳에 있음.
				mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
						new Intent(getApplicationContext(), Message_Detail_Activity.class)
						.putExtra("PK_Mes_Code",Integer.toString(push_pkcode))
						.putExtra("Mes_Category", intent.getStringExtra(PublicConstant.PUSH_MES_CATEGORY))
						, PendingIntent.FLAG_UPDATE_CURRENT));
			}
				//푸시 켜지고 꺼짐.
				if (member.Rank.equals("2")) {				
				mNotificationManager.notify(Integer.parseInt(intent
						.getStringExtra(PublicConstant.PUSH_CODE)),
						mBuilder.build());
				}
	}
			//토스트용.
			if (topActivity.getPackageName().equals("com.defysoft.waukids")) {
			Intent sendintent_one = new Intent("com.defysoft.waukids.TOAST_MESSAGE")
			.putExtra("PUSH_NAME", intent.getStringExtra(PublicConstant.PUSH_NAME))
			.putExtra("PUSH_SUB", intent.getStringExtra(PublicConstant.PUSH_SUB));
			sendBroadcast(sendintent_one);			
			}
			//리프레쉬.
					Intent sendintent_two = new Intent("com.defysoft.waukids.REFRESH")
					.putExtra("PUSH_SENDTYPE", intent.getStringExtra(PublicConstant.PUSH_SENDTYPE));
					sendBroadcast(sendintent_two);	
					
}//푸시메시지 10000번대 끝.
//20000번대 시작
else if ((Integer.parseInt(push_sendtype))>= 20000 && (Integer.parseInt(push_sendtype)) < 30000) {
	if(!onapp){
		mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
				new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
	} else 	if (onapp) {
		if (topActivity.getClassName().equals("com.defysoft.waukids.main.Main_MainFrame")) {
			Intent sendintent_two = new Intent("com.defysoft.waukids.REFRESH")
			.putExtra("PUSH_SENDTYPE", intent.getStringExtra(PublicConstant.PUSH_SENDTYPE));
			sendBroadcast(sendintent_two);	
		}
	}
	if (sharedPreferences.getString("PUSH_FIELD", "0").equals("0")) {
		mNotificationManager.notify(Integer.parseInt(intent
				.getStringExtra(PublicConstant.PUSH_CODE)),
				mBuilder.build());
	}
	
}
// 30000번대 시작
else if((Integer.parseInt(push_sendtype))>= 30000 && (Integer.parseInt(push_sendtype)) < 40000){
	if(!onapp){
		mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),0, 
				new Intent(getApplicationContext(), Main_Intro.class), PendingIntent.FLAG_UPDATE_CURRENT));
	} else if (onapp) {
		if (topActivity.getClassName().equals("com.defysoft.waukids.main.Main_MainFrame")) {
			Intent sendintent_two = new Intent("com.defysoft.waukids.REFRESH")
			.putExtra("PUSH_SENDTYPE", intent.getStringExtra(PublicConstant.PUSH_SENDTYPE));
			sendBroadcast(sendintent_two);	
		}
	}


	
}
			
		} 
		
	}

}